package com.m1905.lib.download.util;


import com.m1905.lib.download.model.DownloadDBItem;

import java.util.List;

/**
 * @author wanghao
 * @date 2023/10/27.
 * @des
 */
public class Utils {
    public static int findDownloadItemFromDownloadListPosition(List<DownloadDBItem> downloadList, DownloadDBItem item) {
        if (item != null && downloadList != null && downloadList.size() > 0) {
            for (int i = 0; i < downloadList.size(); i++) {
                DownloadDBItem it = downloadList.get(i);
                if (item.getId() > 0) {
                    if (it.getId() == item.getId()) {
                        return i;
                    }
                } else {
                    if (item.equals(it)) {
                        return i;
                    }
                }
            }
        }
        return -1;
    }

    public static DownloadDBItem findDownloadItemFromDownloadList(List<DownloadDBItem> downloadList, DownloadDBItem item) {
        if (item != null) {
            for (DownloadDBItem it : downloadList) {
                if (item.getId() > 0) {
                    if (it.getId() == item.getId()) {
                        return it;
                    }
                } else {
                    if (item.equals(it)) {
                        return it;
                    }
                }
            }
        }
        return null;
    }

    public static final int ASYNC_ADD = 0;
    public static final int ASYNC_UPD = 1;
    public static final int ASYNC_DEL = 2;

    public static DownloadDBItem asyncDownload(List<DownloadDBItem> downloadList, DownloadDBItem item, int status) {
        if (downloadList != null && item != null) {
            DLog.e("asyncDownload: " + downloadList.size() + "  " + status + "  " + item);
            if (status == ASYNC_ADD) {
                downloadList.add(item);
                return item;
            } else if (status == ASYNC_DEL) {
                DownloadDBItem target = findDownloadItemFromDownloadList(downloadList, item);
                if (target != null) {
                    downloadList.remove(target);
                    return target;
                }
            } else {
                for (DownloadDBItem it : downloadList) {
                    if (it.getId() == item.getId()) {
                        it.readFrom(item);
                        return it;
                    }
                }
            }
        }
        return null;
    }

    /**
     * @param str 如果str为null时跳过相等判断直接返回true。
     * @param target
     * @return
     */
    public static boolean queryEquals(String str, String target) {
        if (str == null) {
            return true;
        }
        return str.equals(target);
    }

    public static boolean queryEquals(int flags, int flag) {
        return (flags & flag) == flag;
    }
}
